package ops.view.forms;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;

import javax.swing.JPanel;

import ops.view.forms.component.FormInput;

public class Form {
	
	private GridBagConstraints inputConstraint;
	private GridBagConstraints labelConstraint;
	
	private JPanel panel;
	
	private HashMap<String, FormInput> inputs;
	
	public Form() {
		initConstraints();
		
		initPanel();
		
		inputs = new HashMap<String, FormInput>();
	}
	
	private void initPanel() {
		panel = new JPanel(new GridBagLayout());
	}

	private void initConstraints() {
		inputConstraint = new GridBagConstraints();
		inputConstraint.anchor = GridBagConstraints.WEST;
		inputConstraint.gridwidth = 1;
		inputConstraint.fill = GridBagConstraints.NONE;
		inputConstraint.gridx = 1;
		inputConstraint.gridy = 0;
		inputConstraint.insets = new Insets(3, 5, 3, 5);
		
		labelConstraint = (GridBagConstraints) inputConstraint.clone();
		labelConstraint.anchor = GridBagConstraints.EAST;
		labelConstraint.gridx = 0;
		labelConstraint.gridwidth = 1;
	}
	
	private void moveToNextLine() {
		labelConstraint.gridy++;
		inputConstraint.gridy++;
	}
	
	public void addInput(String id, FormInput input) {
		inputs.put(id, input);
		
		panel.add(input.getLabelComponent(), labelConstraint);
		panel.add(input.getInputComponent(), inputConstraint);
		
		moveToNextLine();
	}
	
	public void clear() {
		for (FormInput input : inputs.values()) {
			if (!(input instanceof NonClearableInput)) {
				input.clearInput();
			}
		}
	}
	
	public boolean validate() {
		for (FormInput input : inputs.values()) {
			if (input.isRequired() && 
					(!input.validate() || input.getInputValue() == null || input.getInputValue().toString().equals(""))) {
				return false;
			}
		}
		
		return true;
	}
	
	public JPanel getPanel() {
		return panel;
	}

	public Object getValueFor(String id) {
		return inputs.get(id).getInputValue();
	}
	
	public String getStringFor(String id) {
		return (String) inputs.get(id).getInputValue();
	}
	
	public boolean getBooleanFor(String id) {
		return (Boolean) inputs.get(id).getInputValue();
	}
	
	public int getIntegerFor(String id) {
		return ((Double) inputs.get(id).getInputValue()).intValue();
	}
	
	public long getLongFor(String id) {
		return ((Double) inputs.get(id).getInputValue()).longValue();
	}
	
	public float getFloatFor(String id) {
		return ((Double) inputs.get(id).getInputValue()).floatValue();
	}
	
	public double getDoubleFor(String id) {
		return ((Double) inputs.get(id).getInputValue()).doubleValue();
	}
	
	public void setValue(String id, Object value) {
		inputs.get(id).setInputValue(value);
	}
}
